/*
 * @lc app=leetcode.cn id=599 lang=typescript
 *
 * [599] 两个列表的最小索引总和
 */

// @lc code=start
function findRestaurant(list1: string[], list2: string[]): string[] {
  const map = new Map<string, number>();
  // 记录list1每个餐厅的索引
  for (let i = 0; i < list1.length; i++) {
    map.set(list1[i], i);
  }
  // 遍历list2，找出最小索引和
  const ans = [];
  let minSum = Number.MAX_SAFE_INTEGER;
  for (let i = 0; i < list2.length; i++) {
    const name = list2[i];
    if (!map.has(name)) continue;
    const sum = i + map.get(name);
    if (sum < minSum) {
      minSum = sum;
      ans.length = 0;
      ans.push(name);
    } else if (sum === minSum) {
      ans.push(name);
    }
  }
  return ans;
}
// @lc code=end
